/* 
 * created by senllang 2024/1/1 
 * mail : study@senllang.onaliyun.com 
 *
 * Copyright (c) 2023-2024 senllang

 * This is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 * 
 */
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define THREAD_NAME_LEN 32
__thread char threadName[THREAD_NAME_LEN];
__thread int delay = 0;

typedef struct ThreadData 
{
    char name[THREAD_NAME_LEN];
    int delay;
}ThreadData;

void *threadEntry(void *arg) 
{
    int ret = 0;
    int i = 0;
    ThreadData * data = (ThreadData *)arg;

    printf("[%lu] thread entered \n", pthread_self());

    strncpy(threadName, data->name, THREAD_NAME_LEN);
    delay = data->delay;

    for(i = 0; i < delay; i++)
    {
        usleep(10);
    }
    printf("[%lu] %s exiting after delay %d.\n", pthread_self(), threadName, delay);
    pthread_exit(&ret);
}

int main(int argc, char *argv[]) 
{
    pthread_t thid1,thid2,thid3;
    void *ret;
    ThreadData args1 = {"thread 1", 50000}, args2 = {"thread 2", 25000}, args3 = {"thread 3", 12500};

    strncpy(threadName, "Main Thread", THREAD_NAME_LEN);

    if (pthread_create(&thid1, NULL, threadEntry, &args1) != 0) 
    {
        perror("pthread_create() error");
        exit(1);
    }

    if (pthread_create(&thid2, NULL, threadEntry, &args2) != 0) 
    {
        perror("pthread_create() error");
        exit(1);
    }

    if (pthread_create(&thid3, NULL, threadEntry, &args3) != 0) 
    {
        perror("pthread_create() error");
        exit(1);
    }

    if (pthread_join(thid1, &ret) != 0) 
    {
        perror("pthread_create() error");
        exit(3);
    }

    if (pthread_join(thid2, &ret) != 0) 
    {
        perror("pthread_create() error");
        exit(3);
    }

    if (pthread_join(thid3, &ret) != 0) 
    {
        perror("pthread_create() error");
        exit(3);
    }

    printf("[%s]all thread exited delay:%d .\n", threadName, delay);
}